<?php

namespace addon\ly_shareholder\app\service\core;

use addon\ly_shareholder\app\model\Shareholder;
use addon\ly_shareholder\app\model\ShareholderLevel;
use addon\recharge\app\dict\RechargeOrderDict;
use addon\recharge\app\model\RechargeOrder;
use addon\shop\app\dict\order\OrderDict;
use addon\shop\app\model\order\Order;
use addon\shop\app\model\order\OrderGoods;
use addon\shop_fenxiao\app\model\fenxiao\Fenxiao;
use app\model\member\Member;
use core\base\BaseCoreService;
use think\Model;
use think\facade\Log;


/**
 * 股东等级
 */
class CoreShareholderLevelService extends BaseCoreService
{

    public function __construct()
    {
        parent::__construct();
        $this->model = new ShareholderLevel();
    }

    /**
     * 统一的股东升级处理入口
     * @param int $site_id 站点ID
     * @param int $member_id 会员ID
     * @param array $processed_members 已处理过的会员ID数组，防止循环递归
     * @return bool
     */
    public static function shareholderUpgrade($site_id, $member_id, $processed_members = [])
    {
        Log::write('-----ly_shareholder-----shareholderUpgrade---member_id:' . $member_id);
        // 防止循环递归
        if (in_array($member_id, $processed_members)) {
            return false;
        }
        $processed_members[] = $member_id;
        
        Log::write('-----ly_shareholder----shareholderUpgrade 处理用户ID:' . $member_id);
        try {
            $shareholder_service = new self();
            $config = (new CoreConfigService())->getShareholderConfig($site_id);
            
            // 获取会员信息
            $member = (new Member())->where([
                ['site_id', '=', $site_id], 
                ['member_id', '=', $member_id]
            ])->find();
            
            if (empty($member)) {
                Log::write('-----ly_shareholder----会员不存在：' . $member_id);
                return false;
            }
            
            // 检查是否已经是股东
            $shareholder_info = (new Shareholder())->where([
                ['site_id', '=', $site_id], 
                ['member_id', '=', $member_id]
            ])->findOrEmpty()->toArray();
            
            // 根据是否已是股东进行不同处理
            if (empty($shareholder_info)) {
                // 非股东，尝试成为股东（最低等级）
                $level = $shareholder_service->model->where([
                    ['site_id', '=', $site_id], 
                    ['level_num', '=', 1]
                ])->find();
                
                if (empty($level)) {
                    Log::write('-----ly_shareholder----没有找到等级：level_num=1');
                    return false;
                }
                
                // 获取数据并检查是否满足条件
                $member_data = $shareholder_service->getMemberData($site_id, $member_id, $level['child_level_num']);
                $canBecomeShareholder = $shareholder_service->checkUpgradeCondition($level['upgrade_type'], $member_data, $level);
                
                if ($canBecomeShareholder) {
                    // 处理成为股东
                    Log::write('-----ly_shareholder----成为股东：member_id=' . $member_id);
                    $shareholder_service->processUpgrade(
                        $site_id, 
                        $member_id, 
                        $level['level_id'], 
                        $config, 
                        $member_data, 
                        '自动成为股东', 
                        true
                    );
                }
            } else {
                // 已是股东，尝试升级
                $current_level = $shareholder_service->model->where([
                    ['site_id', '=', $site_id], 
                    ['level_id', '=', $shareholder_info['level_id']]
                ])->find();
                
                if (empty($current_level)) {
                    Log::write('-----ly_shareholder----找不到当前等级信息：level_id=' . $shareholder_info['level_id']);
                    return false;
                }
                
                // 查找下一等级
                $next_level = $shareholder_service->model->where([
                    ['site_id', '=', $site_id], 
                    ['level_num', '>', $current_level['level_num']]
                ])->order('level_num asc')->find();
                
                if (empty($next_level)) {
                    Log::write('-----ly_shareholder----已是最高等级：member_id=' . $member_id);
                    return false;
                }
                
                // 获取数据并检查是否满足升级条件
                $member_data = $shareholder_service->getMemberData($site_id, $member_id, $next_level['child_level_num']);
                $canUpgrade = $shareholder_service->checkUpgradeCondition($next_level['upgrade_type'], $member_data, $next_level);
                
                if ($canUpgrade) {
                    // 处理升级
                    Log::write('-----ly_shareholder----升级股东等级：member_id=' . $member_id . ', level_id=' . $next_level['level_id']);
                    $shareholder_service->processUpgrade(
                        $site_id, 
                        $member_id, 
                        $next_level['level_id'], 
                        $config, 
                        $member_data, 
                        '自动升级股东等级'
                    );
                }
            }
            
            // 处理上级升级检查
            if (!empty($member['pid'])) {
                Log::write('-----ly_shareholder-----处理上级用户：pid=' . $member['pid']);
                self::shareholderUpgrade($site_id, $member['pid'], $processed_members);
            }
            
            return true;
        } catch (\Exception $e) {
            Log::write('股东升级异常: ' . $e->getMessage());
            return false;
        }
    }

    /**
     * 检查是否满足升级条件
     * @param int $upgrade_type 升级类型(0:满足任意条件,1:满足所有条件)
     * @param array $member_data 会员数据
     * @param array $level_info 等级信息
     * @return bool 是否满足升级条件
     */
    public function checkUpgradeCondition($upgrade_type, $member_data, $level_info) {
        // 记录参数信息，方便调试
        Log::write('-----ly_shareholder----checkUpgradeCondition----参数信息: ' . json_encode([
            'upgrade_type' => $upgrade_type,
            'level_info' => $level_info,
        ]));
        
        // 定义所有可能的条件
        $conditions = [
            'order_num' => [
                'enabled' => !empty($level_info['order_num']) && $level_info['order_num'] > 0,
                'satisfied' => $member_data['order_num'] >= $level_info['order_num']
            ],
            'order_money' => [
                'enabled' => !empty($level_info['order_money']) && $level_info['order_money'] > 0,
                'satisfied' => $member_data['order_money'] >= $level_info['order_money']
            ],
            'recharge_money' => [
                'enabled' => !empty($level_info['recharge_money']) && $level_info['recharge_money'] > 0,
                'satisfied' => isset($member_data['recharge_money']) && $member_data['recharge_money'] >= $level_info['recharge_money']
            ],
            'order_goods_id' => [
                'enabled' => !empty($level_info['order_goods_id']),
                'satisfied' => in_array($level_info['order_goods_id'], $member_data['goods_ids'])
            ],
            'child_num' => [
                'enabled' => !empty($level_info['child_num']) && $level_info['child_num'] > 0,
                'satisfied' => $member_data['child_num'] >= $level_info['child_num']
            ],
            'child2_num' => [
                'enabled' => !empty($level_info['child2_num']) && $level_info['child2_num'] > 0,
                'satisfied' => $member_data['child2_num'] >= $level_info['child2_num']
            ],
            'child_level_num' => [
                'enabled' => !empty($level_info['child_level_num']),
                'satisfied' => isset($member_data['can_upgrade']) && $member_data['can_upgrade']
            ]
        ];
        
        // 筛选出启用的条件
        $enabled_conditions = array_filter($conditions, function($condition) {
            return $condition['enabled'];
        });
        
        // 如果没有启用任何条件，则不升级
        if (empty($enabled_conditions)) {
            Log::write('-----ly_shareholder----没有启用任何升级条件');
            return false;
        }
        
        // 根据升级类型进行条件判断
        if ($upgrade_type == 0) {
            // "或"条件：任一条件满足即可
            $result = false;
            foreach ($enabled_conditions as $condition) {
                if ($condition['satisfied']) {
                    $result = true;
                    break;
                }
            }
        } else {
            // "与"条件：所有条件都必须满足
            $result = true;
            foreach ($enabled_conditions as $condition) {
                if (!$condition['satisfied']) {
                    $result = false;
                    break;
                }
            }
        }
        
        Log::write('-----ly_shareholder----checkUpgradeCondition----升级结果: ' . ($result ? 'true' : 'false'));
        return $result;
    }

    /**
     * 获取会员相关数据
     * @param int $site_id 站点ID
     * @param int $member_id 会员ID
     * @param mixed $level_condition 等级条件
     * @return array 会员数据
     */
    public function getMemberData($site_id, $member_id, $level_condition) {
        $data = [];
        
        // 订单数据
        $data['order_money'] = (new Order())->where([['status', '=', OrderDict::FINISH], ['member_id', '=', $member_id], ['site_id', '=', $site_id]])->sum('order_money');
        $data['order_num'] = (new Order())->where([['status', '=', OrderDict::FINISH], ['member_id', '=', $member_id], ['site_id', '=', $site_id]])->count();
        
        // 充值数据 (注释掉的代码保留，可能后续会用到)
        // $data['recharge_money'] = (new RechargeOrder())->where([['order_status', '=', RechargeOrderDict::WAIT_PAY], ['member_id', '=', $member_id], ['site_id', '=', $site_id], ['refund_status', '=', 0]])->sum('order_money');
        
        // 推广数据
        $childNumData = (new CoreShareholderService())->getChildNum($site_id, $member_id);
        $data['child_num'] = $childNumData['child_num'];
        $data['child2_num'] = $childNumData['child2_num'];
        
        // 处理level_condition，解析JSON字符串
        $parsed_level_condition = $level_condition;
        if (is_string($level_condition) && !empty($level_condition)) {
            try {
                $parsed_level_condition = json_decode($level_condition, true);
                Log::write('-----ly_shareholder----level_condition 解析结果: ' . json_encode($parsed_level_condition));
            } catch (\Exception $e) {
                Log::write('-----ly_shareholder----level_condition 解析失败: ' . $e->getMessage());
            }
        }
        
        // 直推某等级人数
        $result = (new CoreShareholderService())->getChildNum($site_id, $member_id, $parsed_level_condition);
        $data['child_level_num'] = $result['match_level_num'] ?? 0;
        $data['can_upgrade'] = $result['can_upgrade'] ?? false;
        
        // 获取购买商品信息
        $goodsIds = [];
        $memberOrders = (new OrderGoods())->where([['status', '=', OrderDict::FINISH], ['member_id', '=', $member_id], ['site_id', '=', $site_id]])->select();
        foreach ($memberOrders as $order) {
            $goodsIdsInOrder = explode(',', $order['goods_id']);
            $goodsIds = array_merge($goodsIds, $goodsIdsInOrder);
        }
        $data['goods_ids'] = $goodsIds;
        
        return $data;
    }
    
    /**
     * 处理升级
     * @param int $site_id 站点ID
     * @param int $member_id 会员ID
     * @param int $level_id 升级到的等级ID
     * @param array|null $config 配置信息
     * @param array $member_data 会员数据
     * @param string $comment 日志备注
     * @param bool $is_add 是否是新增股东(true:新增,false:升级)
     */
    public function processUpgrade($site_id, $member_id, $level_id, $config = null, $member_data = [], $comment = '自动升级', $is_add = false) {
        if ($is_add) {
            // 新增股东
            (new CoreShareholderService())->add($site_id, $member_id, $level_id);
        } else {
            // 升级股东等级
            (new Shareholder())->where([['site_id', '=', $site_id], ['member_id', '=', $member_id]])->update(['level_id' => $level_id]);
        }
        
        // 记录日志
        Log::write([
            'member_id' => $member_id,
            'order_num' => $member_data['order_num'],
            'order_money' => $member_data['order_money'],
            'recharge_money' => $member_data['recharge_money'] ?? 0,
            'child_num' => $member_data['child_num'],
            'child2_num' => $member_data['child2_num'],
            'child_level_num' => $member_data['child_level_num'],
            'order_goods_id' => $member_data['goods_ids'],
            'comment' => $comment,
        ]);
        
        // 如果有配置信息则处理额外功能
        if (!empty($config)) {
            // 自动降级检测
            if(isset($config['auto_downlv']) && $config['auto_downlv'] == 1){
                $this->checkUpgrade($site_id, $member_id, $level_id);
            }

            // 分销等级同步
            if(isset($config['fenxiao_level']) && $config['fenxiao_level'] == 1){
                $this->syncFenxiaoLevel($site_id, $member_id, $level_id);
            }
        }
    }

    /**
     * 升级后判断是否上级平级
     */
    public function checkUpgrade($site_id, $member_id, $upgrade_level_id){
        $member = (new Member())->where([['site_id', '=', $site_id], ['member_id', '=', $member_id]])->find();
        if (empty($member)) return;

        $pid = $member['pid'];
        // 获取升级后的等级信息
        $level = $this->model->where([['site_id', '=', $site_id], ['level_id', '=', $upgrade_level_id]])->find();
        if (empty($level)) return;

        // 获取上级股东信息
        $parent = (new Shareholder())->where([['site_id', '=', $site_id], ['member_id', '=', $pid]])->find();
        if (empty($parent)) return;

        //统计上级股东的下级投东的等级人数
        $child_conut = (new CoreShareholderService())->getChildNum($site_id, $pid, $level['child_level_num']);
        
        // 获取降级后的等级信息
        $down_level = $this->model->where([['site_id', '=', $site_id], ['level_num', '<', $level['level_num']]])->find();

        if ($parent['level_id'] == $level['level_id'] && $child_conut['can_upgrade'] == false) {
            (new Shareholder())->where([['site_id', '=', $site_id], ['member_id', '=', $pid]])->update(['level_id' => $down_level['level_id']]);
            Log::write('==========走到这里了==========', 'INFO');
            Log::write([
                'member_id' => $pid,
                'level_id' => $down_level['level_id'],
                'comment' => '自动降级',
                'child_conut' => $child_conut['match_level_num'],
                'reason' => '下级要求的等级人数不足',
            ]);
        }
        return true;
    }


    /**
     * 同步分销等级
     */
    public function syncFenxiaoLevel($site_id, $member_id, $upgrade_level_id){
        $level = $this->model->where([['site_id', '=', $site_id], ['level_id', '=', $upgrade_level_id]])->find();
        if (empty($level)) return;

        $fenxiao_level = $level['fenxiao_level'];
        if ($fenxiao_level > 0) {
            $fenxiao = (new Fenxiao())->where([['site_id', '=', $site_id], ['member_id', '=', $member_id]])->find();

            $fenxiao->level_id = $fenxiao_level;
            $fenxiao->member_id = $member_id;
            $fenxiao->site_id = $site_id;
            $fenxiao->save();
        }
        
    }


    /**
     * 获取默认股东等级
     * @param $site_id
     * @return ShareholderLevel|array|mixed|Model
     */
    public function findDefaultShareholderLevel($site_id)
    {
        return $this->model->where([['site_id', '=', $site_id]])->findOrEmpty();
    }

    public function findShareholderLevel($site_id, $level_id)
    {
        return $this->model->where([['site_id', '=', $site_id], ['level_id', '=', $level_id]])->findOrEmpty();
    }

    /**
     * 获取所有等级信息
     * @param $site_id 站点ID
     * @return array|\think\Collection
     */
    public function getAllLevel($site_id)
    {
        return $this->model->where([['site_id', '=', $site_id]])->select();
    }

    public function getLevelByMember($site_id, $member){
        $level = $this->model->where([['site_id', '=', $site_id], ['level_id', '=', $member['level_id']]])->findOrEmpty();
        return $level;
    }

}
